#directory : 原存放快捷方式的目录，同时也是新快捷方式的保存目录
#仅适用于磁盘迁移所导致的快捷方式失效
import os
import time
import win32com.client
from win32com.client import Dispatch

directory = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
lnk_path = []
target_path = []
new_target_path = []
replace_target = []
final_list = []
file_name = []
target_file = replace_target
shortcut_path = final_list

def search_lnk_dir(directory):
    for root,dirs,files in os.walk(directory):
        for file_name in files:
            if file_name.endswith(".lnk"):
                file_path = os.path.join(root,file_name)
                lnk_path.append(file_path)
                #print(file_path)           
    print("已遍历完当前目录，共{}个，输出当前目录下所有快捷方式：\n".format(len(lnk_path)))
    # for lnk_name in lnk_path:
    #     print(lnk_name)

def read_lnk_path(lnk_path):
    for lnk_name in lnk_path:
        shell = win32com.client.Dispatch("WScript.Shell")
        shortcut = shell.CreateShortCut(lnk_name)
        targetpath = shortcut.Targetpath
        target_path.append(targetpath)
        # print(targetpath)
        # print(len(targetpath))
    print("已输出所有快捷方式所指向路径\n")
        
def select_path(target_path):
    num = 0
    for target_name in target_path:
        if len(target_name) != 0 and target_name[0] == 'D':      #修改‘D’即可更改筛选目标
            new_target_path.append(target_name)
            final_list.append(lnk_path[num])
            # print(target_name)
            num +=1
        else:
            num += 1
    print("已筛选出所有原指向D盘的快捷方式\n")

def replace(new_target_path):
    for str in new_target_path:
        str= str.replace('D','F',1)                             #修改'F'即可修改目标盘符
        replace_target.append(str)
    # for str in replace_target:
    #     print(str)
    print("已更换盘符\n")

def quire_filename(final_list):
    for str in final_list:
        path = str.split('\\')
        name = path[len(path)-1]
        file_name.append(name)
    # print(file_name)


def rm_oldfile():
    num = 0
    while num < len(shortcut_path):
        os.remove(shortcut_path[num])                        #旧的快捷方式的路径，同时也是新快捷方式的保存路径
        num += 1
    print("删除旧的已失效的快捷方式\n")

def create_new_lnk(target_file,shortcut_path):
    num = 0
    while num < len(shortcut_path):
        shell = Dispatch("WScript.Shell")
        shortcut = shell.CreateShortCut(shortcut_path[num])
        shortcut.TargetPath = target_file[num]
        shortcut.Save()
        num += 1
        time.sleep(1)
    print("成功创建新的快捷方式\n")

def main():
    search_lnk_dir(directory)
    print("已搜索到当前目录下所有快捷方式，共{}个,现输出快捷方式所指向路径：\n".format(len(lnk_path)))
    read_lnk_path(lnk_path)
    select_path(target_path)
    replace(new_target_path)
    quire_filename(final_list)
    # print(final_list)
    # print("\n")
    # print(file_name)
    
    rm_oldfile()
    create_new_lnk(target_file,shortcut_path)
    
    # print(replace_target)
    # print(len(replace_target))
    # print(len(shortcut_path))

if __name__ == "__main__":
    main()